<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/4/17
 * Time: 10:53
 */

require_once(LIB_PATH."geo/Geohash.php");

class mygeo{
    public static $lng = 0;
    public static $lat = 0;
    public static $result = false;

    public static function getOrderBy($lat='',$lng=''){
        if($lat=='') $lat = r('lat');
        if($lng=='') $lng = r('lng');

        $geo = mygeo::getHash($lat,$lng);

        $orderLike1 = substr($geo,0,7);//最近
        $orderLike2 = substr($geo,0,6);
        $orderLike3 = substr($geo,0,5);
        $orderLike4 = substr($geo,0,4);
        $orderLike5 = substr($geo,0,3);

        $orderBy= " geo!='' desc , geo LIKE '$orderLike1%' DESC ";
        $orderBy .= " ,geo LIKE '$orderLike2%' DESC ";
        $orderBy .= " ,geo LIKE '$orderLike3%' DESC ";
        $orderBy .= " ,geo LIKE '$orderLike4%' DESC ";
        $orderBy .= " ,geo LIKE '$orderLike5%' DESC ";

        return $orderBy;
    }

    //纬度在前面
    public static function getHash($lat,$lng,$precision=12){
        self::$lng = $lng;
        self::$lat = $lat;
        if(function_exists("geohash_encode")) {
            return geohash_encode($lat,$lng, $precision);
        };

        //return Geohash::encode(35.6813177190391, 139.76682186000000); //xn76urx4dzxy
        //注意：谷歌地图搜索时前面时纬度，后面是经度
        //return Geohash::encode(35.6813177190391, 139.76600000000000); //xn76urw6xzen
        return Geohash::encode($lat,$lng);   //xn76urd4sp9q
    }

    public static function nearBy($lat,$lng){
        $hash = self::getHash($lat,$lng);
        return geohash_neighbors($hash);
    }

    public static function getJsonInfo($lat,$lng){
        if(self::$lng == $lng && self::$lat == $lat && self::$result){
            return self::$result;

        }
        self::$lng = $lng;
        self::$lat = $lat;
        $key = "FFMBZ-OE7L4-YNLUA-XLLSL-ZHYXK-Y7FSO";

        //搜索
        //https://zhaopeixunapi.hkbao.com/map,desc?location=39.908491,116.374328
        //$url = "https://apis.map.qq.com/ws/place/v1/search?keyword=%E9%85%92%E5%BA%97&boundary=nearby(39.908491,116.374328,1000)&key=$key";
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=$lat,$lng&key=$key&output=JSON";
        myspider::$referer = "https://zhaopeixunapi.hkbao.com/";
        $result = myspider::fetch($url);
        self::$result = json_decode($result);
        return(self::$result);
    }

    public static function getCityByPosition($lat,$lng){
        $result = self::getJsonInfo($lat,$lng);
        //@todo 当获取结果错误时，通过ip地址来获取
        return $result->result->ad_info->city;
    }

    public static function getDistrict($lat,$lng){
        $result = self::getJsonInfo($lat,$lng);
        return $result->result->ad_info->district;
    }

    public static function getLat($uid)
    {
        if (s('lat')) {
            $lat = r('lat');
            myredis::set("latUid$uid",$lat);
            return $lat;
        }
        return myredis::get("latUid$uid");
    }

    public static function getLng($uid)
    {
        if (s('lng')) {
            $lng = r('lng');
            myredis::set("lngUid$uid",$lng);
            return $lng;
        }
        return myredis::get("lngUid$uid");
    }

    public static function getDistanceAuto($startLat,$startLng,$endLat,$endLng){
        $distance = self::getDistanceByArray([$startLat,$startLng],[$endLat,$endLng]);
        if($distance > 100000){
            return ">100km";
        }else if($distance > 1000){
            return round($distance/1000, 1)."km";
        }else{
            return round($distance, 1)."m";
        }
    }

    public static  function getDistance($startLat,$startLng,$endLat,$endLng,$km=false,$decimal=2){
        return self::getDistanceByArray([$startLat,$startLng],[$endLat,$endLng],$km,$decimal);
    }

    public static function getDistanceByArray($from,$to,$km=false,$decimal=2)  {
        sort($from);
        sort($to);

        $EARTH_RADIUS = 6370.996; // 地球半径系数
	    $distance = 0;
		if($from[0] && $from[1]) {
			$distance = $EARTH_RADIUS * 2 * asin(sqrt(pow(sin(($from[0] * pi() / 180 - $to[0] * pi() / 180) / 2), 2) + cos($from[0] * pi() / 180) * cos($to[0] * pi() / 180) * pow(sin(($from[1] * pi() / 180 - $to[1] * pi() / 180) / 2), 2))) * 1000;
		}
        

        if ($km) {
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }

    public static function getCity(){
        //--------通过GPS获得地址,太慢了 getCityByGPS=1 ------------
        if(s('lat') && s('lng') && r('getCityByGPS')){
            $cityInfo =  mygeo::getCityByPosition(s('lat') , s('lng'));
        }else{
            $cityInfo = myip::getAddresInfo();
        }

        $city = new City();
        $all = $city->all('1=1');
        foreach($all as $item){
            if(strstr($cityInfo,$item['cityName'])){
                return $item;
            }
        }

        return ['cityName'=>"深圳",'cityIdOk'=>1];//默认，感觉通过ip获得地址更快更好

    }

    public static function getDistrictByCity($city){
        $district = new District();
        $district->cityIdOk = $city['cityIdOk'];
        return $district->all($district->getConByLoad());
    }
}
